package networking;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import com.google.protobuf.CodedInputStream;

import dps.DpsMain;
import dps.DpsMessageProto.DpsMessage;

public class DatagramServerThread extends Thread {
	protected MulticastSocket socket = null;
	
	public DatagramServerThread() throws IOException {
		this("DatagramServerThread", DpsMain.LOCAL_PORT);		
	}
	
	public DatagramServerThread(String name, int port) throws IOException {
		try {			
			// create receiver socket with local port AND local interface's IP address
			socket = new MulticastSocket(port);
			socket.joinGroup(InetAddress.getByName(DpsMain.REMOTE_IP));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}		
	}	
	
	public void run() {
		while(true) {
			byte[] buffer = new byte[1500];
			DatagramPacket packet = new DatagramPacket(buffer, 1500);
			try {
				socket.receive(packet);
//				System.out.println(packet.getData());
				DpsMessage msg = DpsMessage.parseFrom(CodedInputStream.newInstance(packet.getData(), 0, packet.getLength()));
				DpsMain.addBuff(msg);
				System.out.println(msg.getMessageType() + " : " + msg.getPollVote() + " : " + msg.getPollParam() + " " + packet.getSocketAddress().toString() + " voterId:" + msg.getVoterId()+ " pollId:" + msg.getPollId());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
